//
//  MDHNavigationController.m
//  MDHPT
//
//  Created by 高得华 on 2019/4/27.
//  Copyright © 2019年 高得华. All rights reserved.
//

#import "MDHNavigationController.h"
#import "MDHViewController.h"
#import "MDHMacro.h"
#import "NSObject+MDHNSObject.h"

@interface MDHNavigationController ()
<
UINavigationControllerDelegate,
UIGestureRecognizerDelegate
>

/// 导航栏分隔线
@property (nonatomic , weak , readwrite) UIImageView * navigationBottomLine;
@end

@implementation MDHNavigationController

// 第一次使用这个类调用一次
+ (void)initialize{
    // 2.设置UINavigationBar的主题
    [self _setupNavigationBarTheme];
    
    // 3.设置UIBarButtonItem的主题
    [self _setupBarButtonItemTheme];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 初始化
    [self _setup];
    self.interactivePopGestureRecognizer.delegate = self;
}

#pragma mark - 初始化
- (void) _setup
{
    [self _setupNavigationBarBottomLine];
}

// 查询最后一条数据
- (UIImageView *)_findHairlineImageViewUnder:(UIView *)view{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews){
        UIImageView *imageView = [self _findHairlineImageViewUnder:subview];
        if (imageView){ return imageView; }
    }
    return nil;
}

#pragma mark - 设置导航栏的分割线
- (void)_setupNavigationBarBottomLine {
    //!!!:这里之前设置系统的 navigationBarBottomLine.image = xxx;无效 Why？ 隐藏了系统的 自己添加了一个分割线
    // 隐藏系统的导航栏分割线
    UIImageView *navigationBarBottomLine = [self _findHairlineImageViewUnder:self.navigationBar];
    navigationBarBottomLine.hidden = true;
    // 添加自己的分割线
    CGFloat navSystemLineH = .5f;
    UIImageView *navSystemLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.navigationBar.bounds) - navSystemLineH, [UIScreen mainScreen].bounds.size.width, navSystemLineH)];
    navSystemLine.backgroundColor = [UIColor colorWithRed:223.0f/255 green:223.0f/255 blue:223.0f/255 alpha:1.0f];
    [self.navigationBar addSubview:navSystemLine];
    self.navigationBottomLine = navSystemLine;
}


/**
 *  设置UINavigationBarTheme的主题
 */
+ (void) _setupNavigationBarTheme {
    UINavigationBar *appearance = [UINavigationBar appearance];
    
    /// 设置背景
    //!!!: 必须设置为透明  不然布局有问题 ios8以下  会崩溃/ 如果iOS8以下  请再_setup里面 设置透明 self.navigationBar.translucent = YES;
    appearance.translucent = true;
    //[appearance setTranslucent:true]; /// 必须设置true
    
    // 设置导航栏的样式
    [appearance setBarStyle:UIBarStyleDefault];
    //设置导航栏文字按钮的渲染色
    [appearance setTintColor:[UIColor blackColor]];//[UIColor whiteColor]
    // 设置导航栏的背景渲染色
    //CGFloat rgb = 0.1;[UIColor colorWithRed:rgb green:rgb blue:rgb alpha:0.65]
    [appearance setBarTintColor:[UIColor whiteColor]];
    // 设置文字属性
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:18.0f];
    textAttrs[NSForegroundColorAttributeName] = [UIColor blackColor];//[UIColor whiteColor];
    
    // UIOffsetZero是结构体, 只要包装成NSValue对象, 才能放进字典\数组中
    NSShadow *shadow = [[NSShadow alloc] init];
    shadow.shadowOffset =  CGSizeZero;
    textAttrs[NSShadowAttributeName] = shadow;
    [appearance setTitleTextAttributes:textAttrs];
    
    /// 去掉导航栏的阴影图片
    [appearance setShadowImage:[UIImage new]];
    
    ///
    ///返回按钮[backButtonImage ]
    UIImage * backButtonImage = [[UIImage imageNamed:kCommonNavButtonBack] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];//[[[UIImage imageNamed:kCommonNavButtonBack] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    appearance.backIndicatorImage = backButtonImage;
    appearance.backIndicatorTransitionMaskImage = backButtonImage;
    
    if (@available(iOS 11.0, *)) {
        //大标题
        appearance.prefersLargeTitles = false;
    } else {
        // Fallback on earlier versions
    }
}

/**
 *  设置UIBarButtonItem的主题
 */
+ (void)_setupBarButtonItemTheme {
    // 通过appearance对象能修改整个项目中所有UIBarButtonItem的样式
    UIBarButtonItem * appearance = [UIBarButtonItem appearance];
    
    CGFloat fontSize = 15.0f;
    /**设置文字属性**/
    // 设置普通状态的文字属性
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSForegroundColorAttributeName] = [UIColor blackColor];
    textAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:fontSize];
    NSShadow *shadow = [[NSShadow alloc] init];
    shadow.shadowOffset =  CGSizeZero;
    textAttrs[NSShadowAttributeName] = shadow;
    [appearance setTitleTextAttributes:textAttrs forState:UIControlStateNormal];
    
    
    // 设置高亮状态的文字属性
    NSMutableDictionary *highTextAttrs = [NSMutableDictionary dictionaryWithDictionary:textAttrs];
    highTextAttrs[NSForegroundColorAttributeName] = [[UIColor blackColor] colorWithAlphaComponent:.5f];
    [appearance setTitleTextAttributes:highTextAttrs forState:UIControlStateHighlighted];
    
    // 设置不可用状态(disable)的文字属性
    NSMutableDictionary *disableTextAttrs = [NSMutableDictionary dictionaryWithDictionary:textAttrs];
    disableTextAttrs[NSForegroundColorAttributeName] = [[UIColor blackColor] colorWithAlphaComponent:.5f];
    [appearance setTitleTextAttributes:disableTextAttrs forState:UIControlStateDisabled];
}


#pragma mark - Publi Method
/// 显示导航栏的细线
- (void)showNavigationBottomLine { self.navigationBottomLine.hidden = false; }
/// 隐藏导航栏的细线
- (void)hideNavigationBottomLine{ self.navigationBottomLine.hidden = true; }


/// 能拦截所有push进来的子控制器
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    NSString * title = @"";
    // 如果现在push的不是栈底控制器(最先push进来的那个控制器)
    if (self.viewControllers.count > 0) {
        /// 隐藏底部tabbar
        viewController.hidesBottomBarWhenPushed = true;
        /// eg: [A push B]
        /// 1.取出当前的控制器的title ， 也就是取出 A.title
        /// CoderMikeHe Fixed: [[self topViewController] navigationItem].title 这样来获取title 而不是[[self topViewController] title]
        //title = [[self topViewController] navigationItem].title?:@"返回";
        
        /// 2.判断要被Push的控制器（B）是否是 MHViewController ，
        if ([viewController isKindOfClass:[MDHViewController class]]) {
            MDHViewModel *viewModel = [(MDHViewController *)viewController viewModel];
            /// 3. 查看backTitle 是否有值
            title = viewModel.backTitle?:title;
        }
        // 4.这里可以设置导航栏的左右按钮 统一管理方法
        //viewController.navigationItem.leftBarButtonItem = [UIBarButtonItem mh_backItemWithTitle:title imageName:@"barbuttonicon_back_15x30" target:self action:@selector(_back)];
    }
    viewController.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:nil action:nil];
    // push
    [super pushViewController:viewController animated:animated];
}
/// 事件处理
- (void)_back {
    [self popViewControllerAnimated:true];
}

#pragma mark - Override
- (BOOL)shouldAutorotate {
    return self.topViewController.shouldAutorotate;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return self.topViewController.supportedInterfaceOrientations;
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return self.topViewController.preferredStatusBarStyle;
}

- (BOOL)prefersStatusBarHidden{
    return self.topViewController.prefersStatusBarHidden;
}


#pragma mark - 按钮
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
    if([self.viewControllers count] < [navigationBar.items count]) {
        return YES;
    }
    
    BOOL shouldPop = YES;
    UIViewController * vc = [self topViewController];
    if([vc respondsToSelector:@selector(navigationShouldPopOnBackButton)]) {
        shouldPop = [vc navigationShouldPopOnBackButton];
    }
    
    if(shouldPop) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self popViewControllerAnimated:YES];
        });
    } else {
        for(UIView *subview in [navigationBar subviews]) {
            if(0. < subview.alpha && subview.alpha < 1.0) {
                [UIView animateWithDuration:0.25 animations:^{
                    subview.alpha = 1.0;
                }];
            }
        }
    }
    return false;
}
///
- (BOOL)gestureRecognizerShouldBegin:(UIPanGestureRecognizer *)gestureRecognizer {
    if (self.viewControllers.count <= 1) {
        return false;
    } else {
        return true;
    }
}

@end
